package com.toolbox.alui.taglib;

import com.plumtree.openfoundation.util.XPException;
import com.plumtree.openlog.OpenLogService;
import com.plumtree.openlog.OpenLogger;
import com.plumtree.portaluiinfrastructure.statichelpers.PTDebugHelpers;
import com.plumtree.portaluiinfrastructure.tags.ATag;
import com.plumtree.portaluiinfrastructure.tags.Scope;
import com.plumtree.portaluiinfrastructure.tags.TagType;
import com.plumtree.portaluiinfrastructure.tags.metadata.AttributeType;
import com.plumtree.portaluiinfrastructure.tags.metadata.ITagMetaData;
import com.plumtree.portaluiinfrastructure.tags.metadata.OptionalTagAttribute;
import com.plumtree.portaluiinfrastructure.tags.metadata.RequiredTagAttribute;
import com.plumtree.portaluiinfrastructure.tags.metadata.TagMetaData;
import com.plumtree.taglib.logic.LogicTagLibraryData;
import com.plumtree.uiinfrastructure.activityspace.AActivitySpace;
import com.plumtree.uiinfrastructure.constants.AccessStyles;
import com.plumtree.xpshared.htmlelements.HTMLElement;
import com.toolbox.alui.common.helpers.ServerHelper;

/**
 * <p>
 * This tag converts an Object UUID into its corresponding ObjectID and ClassID values.
 * Both values are stored into tag variables for easy reuse with other tags.
 * <p>
 * Sample Usage:
 * <p>
 * &lt;pt:aluitoolbox.convertuuidtoids pt:uuid=&quot;{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}&quot; /&gt;
 * ObjectID: &lt;pt:logic.value pt:value=&quot;$objectid&quot;/&gt;
 * ClassID: &lt;pt:logic.value pt:value=&quot;$classid&quot;/&gt;
 * 
 * @author Fabien Sanglier
 * @category ALUI Toolbox Tags 
 */
public class ConvertUUIDTag extends ATag {
	private static OpenLogger log = OpenLogService.GetLogger(
			OpenLogService.GetComponent(PTDebugHelpers.COMPONENT_PORTAL_UI_INFRASTRUCTURE),
			"com.toolbox.alui.taglib.ConvertUUIDTag");

	public static final ITagMetaData TAG;
	public static final RequiredTagAttribute UUID;
	public static final OptionalTagAttribute KEY_OBJECTID;
	public static final OptionalTagAttribute KEY_CLASSID;
	public static final OptionalTagAttribute SCOPE;
	
	static
	{
		// The TAG member variable needs to be initialized first since it
		// can be used in other tags (i.e. as a RequiredParentTag) that
		// are referenced by member variables of this tag (i.e. as a
		// RelatedChildTag).  This is necessary for tags that have
		// circular references such as a parent / child tag relationship.
		TAG = new TagMetaData("convertuuidtoids",
			"This tag displays user preference for a portlet.");

		UUID = new RequiredTagAttribute("uuid",
			"This attribute specifies the object uuid.",
			AttributeType.STRING);

		KEY_OBJECTID = new OptionalTagAttribute("objectid",
				"This attribute specifies the objectid key used to store the objectid variable in memory." +
				"If not specified, the key is by default 'objectid'.",
				AttributeType.STRING, "objectid");
		
		KEY_CLASSID = new OptionalTagAttribute("classid",
				"This attribute specifies the objectid key used to store the objectid variable in memory." +
				"If not specified, the key is by default 'classid'.",
				AttributeType.STRING, "classid");
		
		SCOPE = new OptionalTagAttribute("scope",
				"The scope used to store the variable.  " + LogicTagLibraryData.SCOPE_REFERENCE,
				AttributeType.STRING, Scope.PORTLET_REQUEST.toString());
	}
	
	/**
	 * @see com.plumtree.portaluiinfrastructure.tags.ATag#DisplayTag()
	 */
	public HTMLElement DisplayTag()
	{
		ServerHelper oHelper = new ServerHelper((AActivitySpace)GetEnvironment());
		
		String strUUID = GetTagAttributeAsString(UUID);
		String strKeyObjectId = GetTagAttributeAsString(KEY_OBJECTID);
		String strKeyClassId = GetTagAttributeAsString(KEY_CLASSID);
		
		Scope scope = Scope.GetScope(GetTagAttributeAsString(SCOPE));

		if (null == scope)
		{
			log.Warn("Unable to convert scope attribute " +
				GetTagAttributeAsString(SCOPE) + " to a valid scope in Tag " +
				TAG.GetName() + ".");

			scope = Scope.PORTLET_REQUEST;
		}
		
		int classID;
		int objectID;
		
		if(null != strUUID && !"".equals(strUUID)){
			try{
				Object[] oClassIDObjectID = oHelper.getClassObjectID(strUUID);
				
				try{
					classID = Integer.parseInt(oClassIDObjectID[0].toString());
				} catch (Exception exc){
					classID = 0;
				}
				
				try{
					objectID = Integer.parseInt(oClassIDObjectID[1].toString());
				} catch (Exception exc){
					objectID = 0;
				}
				
				//save the value
				if(classID > 0){
					// Store the data object using the specified name.
					SetStateSharedVariable(strKeyClassId, new Integer(classID), scope, false);
				}
				
				//save the value
				if(objectID > 0){
					// Store the data object using the specified name.
					SetStateSharedVariable(strKeyObjectId, new Integer(objectID), scope, false);
				}
			} catch (XPException exc){
				log.Error("An error occurred during UUID operation. " +
						"Make sure the uuid format is correct: " +
						"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} where X is between 0 and F (hexadecimal).", exc);
				throw exc;
			}
		} else {
			XPException exc = new XPException("The parameter UUID cannot be null. Please enter a valid Object UUID. " +
					"Format: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} where X is between 0 and F (hexadecimal).");
			log.Error("The parameter UUID cannot be null. Please enter a valid Object UUID. " +
					"Format: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} where X is between 0 and F (hexadecimal).", exc);
			throw exc;
		}
		
		return null;
	}
	
	/**
	 * @see com.plumtree.portaluiinfrastructure.tags.ATag#GetTagType()
	 */
	public TagType GetTagType()
	{
		// This tag does not display any of the HTML inside the tag,
		// and must be used as a singleton tag.
		return TagType.NO_BODY;
	}

	/**
	 * @see com.plumtree.portaluiinfrastructure.tags.ATag#SupportsAccessStyle(AccessStyles)
	 */
	public boolean SupportsAccessStyle(AccessStyles _style)
	{
		// This tag does not display any JavaScript, and therefore
		// supports all access styles.
		return true;
	}
	/**
	 * @see com.plumtree.portaluiinfrastructure.tags.ATag#Create()
	 */
	public ATag Create()
	{
		return new ConvertUUIDTag();
	}	

}
